/* ------------------------------------------------------------------------
	Class: hgallery
	Use: Gallery plugin for jQuery
	Author: Hoang Tran
    Used specifically for hvn to load different sized image if some size is not available.
	Version: 1.1
    Notation: _myLocalFunction()
            $.fn.hgallery.myPublicFunction()
    See http://www.learningjquery.com/2007/10/a-plugin-development-pattern
------------------------------------------------------------------------- */

// create closure
(function($) {
    // plugin definition
    $.fn.hgallery = function(options) {
        // build main options before element iteration. Make it local
        var opts = $.extend({}, $.fn.hgallery.defaults, options);
        
        //_initializeGallery(opts);
        
        // return jquery object
        return this.each(function() {
            // Global variables needed in multiple functions.   
            // but they stay local for each gallery
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            var $galleryWrapper = $(this);
            
            // navigation
            var imageIndex = 0;
            var imageTotal = $galleryWrapper.find("ul.hgallery_ul li").size();
            var $currentThumb ;//= $galleryWrapper.find("ul.hgallery_ul li:first img");
            var pageIndex = 1;
            var pageTotal = 0;
            var pageTotal = Math.ceil(imageTotal / o.itemsPerPage);
            // settings            
            // var itemWidth = 0;
            // var itemHeight = 0;
            var galleryWidth = 0;//$galleryWrapper.width();
            var animated = false;
            
            var $mainImage = $galleryWrapper.find("img.hgallery_main_image");
           // var animationSpeed  = 2000;
            // build element specific options (if metadata plugin is available only)
            // bind the thumbnail image.click
            
//            imgWidth = o.itemWidth * 4.5;
//            imgHeight = o.itemHeight * 3.6;
//            $galleryWrapper.find("div.hgallery_main_image_div").css({'width': imgWidth + 'px', 'height': imgHeight + 'px'});
//            $galleryWrapper.find("div.hgallery_item_navigation").css({'width': imgWidth + 'px', 'height': 20 + 'px'});
//            $galleryWrapper.find("div.ul_wrapper").css({'width': imgWidth + 'px', 'height': o.itemHeight + 2 * o.itemMargin + 'px'});
			//TODO: needs to unbind all the events here first
			
                    
            $galleryWrapper.find("ul.hgallery_ul li").each(function(i)
            {
          		$(this).css({'margin-left':o.itemMargin, 'margin-right':o.itemMargin,'border-width':o.itemBorderWidth + 'px', 'width': o.itemWidth + 'px', 'height': o.itemHeight + 'px'}).addClass('hgallery_li_normal');
                //css the img to be in the center.
                var $thumb = $(this).find('img');
                $thumb.addClass('hgallery_thumbnail_normal')
                .unbind('load').unbind('click')
                .load(function(){
                	
                     $(this).css({"display" : "inline"});
                    imgHeight = $(this).height();
                    marginTop = parseFloat ((o.itemHeight - imgHeight)/2);
                    
                    $(this).css({"margin-top" : marginTop});
                    
                    //alert($(this).attr('src') + ' ' + o.itemHeight + ' ' + imgHeight);
                })
                .click(function(){
                    //console.log('src=' + $currentThumb.attr('src'));
                    if (typeof($currentThumb) != 'undefined' && $currentThumb.attr('src') == $(this).attr('src')) //first time
                    {
                        return false;
                    }
                    if (typeof($currentThumb) != 'undefined') //first time
                    {
                        $mainImage.hide();//todo .parent().addClass('loading');
                        $currentThumb.removeClass('hgallery_thumbnail_focused').addClass('hgallery_thumbnail_normal');
                        //the li
                        $currentThumb.parent().removeClass('hgallery_li_focused').addClass('hgallery_li_normal');
                    }
                    $currentThumb = $(this);
                    $currentThumb.removeClass('hgallery_thumbnail_normal').addClass('hgallery_thumbnail_focused');
                    
                    $currentThumb.parent().removeClass('hgallery_li_normal').addClass('hgallery_li_focused');
                    //$currentThumb.parent().css({'border-color':'red'});
                    //update imageIndex
                    imageIndex = i;
                    _updateImageIndex();
                    
                    //update main image
                    _updateMainImage(o.mainImageSize);     
                })
                .trigger('load');   
            });
            
            //bind the image thumbnails prev/next/click event
            $galleryWrapper.find(".hgallery_item_next").unbind('click').click(function(){
			   	if (imageIndex == imageTotal -1)
               	{        
					clearInterval(playSlideshow);
               		$(".hgallery_item_play").find("img").attr('src', playImgSrc);
              		stopped = 1;
               		if(o.autoloop == 1)
               			$(".hgallery_item_play").click();
				}                    
                else
                {
                	$currentThumb.parent().next().find("img").trigger("click");
               		_updatePagingFromItemNextPrev();
               	}
            });
        
            $galleryWrapper.find(".hgallery_item_prev").unbind('click').click(function(){
                if (imageIndex == 0)
                    return true;
                if(stopped == 0)
                	$(".hgallery_item_play").click();
                $currentThumb.parent().prev().find("img").trigger("click");
                _updatePagingFromItemNextPrev();
            });

			var playSlideshow;
			var stopped =1;
			var playImgSrc = $galleryWrapper.find(".hgallery_item_play img").attr('src');
			var stopImgSrc = $galleryWrapper.find(".hgallery_item_stop img").attr('src');
            $galleryWrapper.find(".hgallery_item_play").unbind('click').click(function(){
            	if (stopped == 1)
            	{
           		 	if(imageIndex == imageTotal -1)
            		{
            			imageIndex = 0;
            			$galleryWrapper.find("ul.hgallery_ul li:first img").trigger("click");
	      				$galleryWrapper.find('ul.hgalery_page_navigation_ul li.next a').addClass('disabled');
            			
		            	animated = true;
	                	$galleryWrapper.find('ul.hgallery_ul').animate({left:'+='+(galleryWidth*(pageIndex-1))},o.timePaging, function(){
	               			animated = false; pageIndex = 1; _updatePaging();
	               		});
            		}              
                	playSlideshow = setInterval( function(){slideSwitch.apply($galleryWrapper) }, o.animateSpeed);
                	stopped = 0;//start playing
                	$(this).find("img").attr('src', stopImgSrc);
                }
               else if(stopped == 0)
           		{
           			stopped = 1 ;//stop playing
               		clearInterval(playSlideshow);
               		$(this).find("img").attr('src', playImgSrc);
               }
            });
            
			function slideSwitch() {
                $(".hgallery_item_next").click();
            }
            
            // bind main image .load & .error (load failed) events 
            $mainImage.unbind('load').unbind('error')
                .load(function(){
                    //$(this).css({"position" : "absolute"});
                    divHeight = $galleryWrapper.find("div.hgallery_main_image_div").height();
                    imgHeight = $(this).height();
                    marginTop = parseFloat ((divHeight - imgHeight)/2);
                    $(this).css({"margin-top" : marginTop});
                    
                    //hide the "...loading" text
                    //$mainImage.parent().removeClass('loading');
                    //show image
                    $(this).fadeIn(1000);
                })
                .error(function(){
                    //perhaps the 'medium' image doesn't exist, now load the 'small'
                    if ($(this).attr('name') == 'xlarge')
                        _updateMainImage('large');
                    else if ($(this).attr('name') == 'large')
                        _updateMainImage('medium');
                    else if ($(this).attr('name') == 'medium')
                        _updateMainImage('small');
                    else if ($(this).attr('name') == 'small')
                        _updateMainImage('xsmall');
                       
                    
            });
                        
            //bind Paging events
            $galleryWrapper.find('ul.hgalery_page_navigation_ul li.prev a').unbind('click').bind('click',function(){
                _prevPageHandler(this);
                return false;
            });
            $galleryWrapper.find('ul.hgalery_page_navigation_ul li.next a').unbind('click').bind('click',function(){
                _nextPageHandler(this);
                return false;
            });
            
            // private functions
            var _updateImageIndex = function()
            {
                $galleryWrapper.find("span.imageIndex").text(imageIndex + 1);
                //update the paging if nec. as well
            }
            
            // paging prev/next handlers
            var _prevPageHandler = function(caller) {
                // Make sure not to double animate, and not animate of the button is disabled
                if(animated || $(caller).hasClass('disabled'))
                    return;

                animated = true;
                //move
                $galleryWrapper.find('ul.hgallery_ul').animate({left:'+='+galleryWidth},o.timePaging, function(){animated = false;});                
            
                pageIndex--;
                _updatePaging();
            };
            
            // paging next handlers
            var _nextPageHandler = function(caller) {
                // Make sure not to double animate, and not animate of the button is disabled
                if(animated || $(caller).hasClass('disabled')) return;
                animated = true;
                
                $galleryWrapper.find('ul.hgallery_ul').animate({left:'-='+galleryWidth},o.timePaging, function(){animated = false;});
                pageIndex++;
                _updatePaging();
            };    
            
        
            var _updatePaging = function() {
        
                $galleryWrapper.find('span.pageIndex').text(pageIndex);
                $galleryWrapper.find('span.pageTotal').text(pageTotal);
                
                // Make sure all the links are enabled
                $galleryWrapper.find('ul.hgalery_page_navigation_ul li a').removeClass('disabled');
                // Display the proper nav
                if(pageIndex == 1){
                    // Hide the previous button
                    $galleryWrapper.find('ul.hgalery_page_navigation_ul li.prev a').addClass('disabled');
                } 
                if(pageIndex == pageTotal) {
                    // Hide the next button
                    $galleryWrapper.find('ul.hgalery_page_navigation_ul li.next a').addClass('disabled');
                };
            };    
            
            var _updatePagingFromItemNextPrev = function()
            {
                var tmpPage = Math.ceil((imageIndex + 1) / o.itemsPerPage);
                if (tmpPage == (pageIndex + 1))
                    $galleryWrapper.find('ul.hgalery_page_navigation_ul li.next a').trigger('click');
                else if (tmpPage == (pageIndex - 1))
                    $galleryWrapper.find('ul.hgalery_page_navigation_ul li.prev a').trigger('click');
            }
            
            /* src = image src of the thumbnail */ 
            var _updateMainImage = function(newSize)
            {
                var src = $currentThumb.attr('src');
                var label = $currentThumb.attr('alt');
                //$mainImage.hide().parent().addClass('loading');
                
                //regex to get larger image here
                var p = /^\/public\/ufiles\/(\d+)\/images\/([^\/]*)\/(.*)/;
                var r = "/public/ufiles/$1/images/" + newSize + "/$3";
                newSrc = src.replace(p, r);
                $mainImage.attr('name', newSize);
                $mainImage.css('margin-top',0).attr("src",newSrc );
                
                //TODO: update the label as well
            }

            _initialize();
            function _initialize()
            {
                //now trigger the click on the first image
                _updatePaging();
                $galleryWrapper.find("span.imageTotal").text(imageTotal);
                _updateImageIndex();
                
                //var pageTotal = Math.ceil($(this).find('li').size() / o.itemsPerPage);
                //fix CSS
                var itemTotalWidth = o.itemWidth + 2 * (o.itemMargin + o.itemBorderWidth);
                var ulWidth = itemTotalWidth * $galleryWrapper.find("ul.hgallery_ul").find('li').size();
                
                //galleryWidth is the actually width of 'itemsPerPage" li(s) displayed
                //inside the ulWrapper. This is used to scroll/animate the li list
                galleryWidth = itemTotalWidth * o.itemsPerPage;///* all li items*/ + 2 * o.urWrapperBorder /* 2 borders both sides*/;
                //ur wrapper
                $galleryWrapper.find("div.ul_wrapper").css({'width':galleryWidth - 2, 'border-width':o.urWrapperBorderWidth + 'px'});// ul wrapper without borders
                
                //actual ul (list of all li(s) )
                $galleryWrapper.find("div.ul_wrapper").find('ul').width(ulWidth + 10); //the horizonal ul
                
                //width of the gallery
                $galleryWrapper.width(galleryWidth + 2*o.urWrapperBorderWidth);//width = ul wrapper with out border + 2*borders
                //alert($galleryWrapper.width());
                //width of the main image wrapper DIV
                //equals size of galleryWidth;
                $galleryWrapper.find("div.hgallery_main_image_div").width(galleryWidth).height(galleryWidth);
                $galleryWrapper.find("div.hgallery_item_navigation").width(galleryWidth);
                //ul height
                ulHeight = o.itemHeight + 2* parseInt(o.itemTopMargin);
                $galleryWrapper.find("ul.hgallery_ul").css({'height': ulHeight});

                //hgalery_page_navigation_ul width
                $galleryWrapper.find("ul.hgalery_page_navigation_ul").width(galleryWidth - 42).css({"display":"none"}); /*TODO: only temporary*/
               	$galleryWrapper.find("ul.hgallery_ul li:first img").trigger("click");
               	
               	//autoplay when view gallery
               	if(o.autoplay == true)
               		$(".hgallery_item_play").trigger("click");			
            }            
        }); //end return .each
    }; //end .fn.hgallery
    
    $.fn.hgallery.defaults = {
        /*galleryWrapper: '';*/
        /*item = li*/
        itemsPerPage : 2,
        //animationSpeed : 'normal', /* fast/normal/slow */
        animateSpeed: 2000,// interval between two autoclick next buttons
        itemWidth : 60, /*not including border*/
        itemHeight : 60, /*pixels*/
        itemMargin: 2, /*left-right Margin for li */
	    itemTopMargin: 2, /* margin from li to ul */        
        itemBorderWidth: 2,
        urWrapperBorderWidth:2, /* border around the itemsPerPage list */
        mainImageSize: 'medium', /* medium/large/small/xsmall/original */
        autoloop : false,  //true or false
        autoplay : false,  //true or false
       	timePaging:500,			//interval return the first li tag ,next or prev page 
    };
    

    // public functions. Only applicable to generic functions which probably do not involve the 
    // $.xxx.defaults object..
    /*
    $.fn.hgallery.format = function(txt) {
        return '<strong>' + txt + '</strong>';
    };
    */
})(jQuery);
